<template>
    <div class="table">
      <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                  <span class="container-title-p">
                    权限管理
                    <i class="iconfont icon-jiantou"></i>
                  </span>
                  <span>子管理员</span>
                  </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
          <div class="u_list_item">  
             <el-button type="success" icon="plus" @click="addNewAccount"><i class="iconfont icon-add-s" style="font-size:14px;margin-right:5px;"></i>添加账号</el-button>
          </div>
        <div class="handle-box">
          <el-table :data='userCenter'>
            <el-table-column prop="avatar" label="头像" align="center">
              <template slot-scope="scope">
                <img :src='scope.row.avatar' width="80px" alt='头像'/>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="用户名" align="center">
            </el-table-column>
            <el-table-column prop="loginName" label="登录名" align="center">
            </el-table-column>
            <el-table-column prop="phone" label="手机号" align="center">
            </el-table-column>
            <el-table-column prop="country.chineseName" label="国家" align="center">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center" width='400'>
              <template slot-scope="scope">
                <el-button type='' @click='adminDetail(scope.row)' :disabled="scope.row.status==1" size='small'>信息查看</el-button>
                <el-button type='success' @click='editAdmin(scope.row)' :disabled="scope.row.status==1" size='small'>编辑</el-button>
                <el-button type='danger' @click='deleteDialog(scope.row)' :disabled="scope.row.status==1" size='small'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- <el-row>
            <el-col :span="5" v-for="(item, index) in userCenter" :key='index'   style="margin:10px;">
              <el-card :body-style="{ padding: '0px' }" style="margin-bottom:20px;">
                <div style="padding: 14px;">  
                  <div class="u_list_item">
                    头像：  
                  <span class="m_avatar">
                    <img :src="item.avatar" class="image" style="width:100%;border-radius:5px;">
                  </span> 
                  <br>
                  <span>
                    用户名：{{item.username}}</span>
                  </div>
                  <div>
                  <el-button v-for='(item_auth,index) in item.auth' type="success" plain class="btn-info auth_item" :key='index'>{{item_auth}}</el-button>
                  
                  </div>
                  <div class="bottom clearfix">
                    <el-button type="primary" @click="editAdmin(item)" class="button">修改信息</el-button>
                    <el-button type="" @click="iceUinfo(item)"  class="button" :class="item.state==1?'':'danger_text'">{{item.state==1?'立即冻结':'取消冻结'}}</el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row> -->
          <div class="pagination">
            <el-pagination
              :page-size="params.size"
              @current-change ="handleCurrentChange"
              layout="prev, pager, next"
              :total="all_page">
            </el-pagination>
          </div>
        </div>


  <el-dialog title="用户信息" :visible.sync="editMinfo">
  <el-form label-width="80px">
      <el-form-item label="头像:">
      <el-upload 
      :disabled="isview"
       name='image'
      :action="uploadURI" 
      :http-request='uploadAvatar'  
      :show-file-list="true"
      :file-list="userAvatar" 
      :on-success="handleAvatarSuccess"
      :limit='1'
      :on-exceed='exceed'
      list-type='picture-card'>
        <!-- <img v-if="adminParams.avatar" :src="unewdata.showavatar" class="avatar"> -->
        <i  class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" size="tiny">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="用户名:">
    <el-input :disabled="isview" v-model="adminParams.username" auto-complete="off"  placeholder="请输入用户名" class="handle-input"></el-input>
    </el-form-item>
    <el-form-item label='登录名:'>
      <el-input :disabled="isview" @blur="getUsername" auto-complete="off" v-model='adminParams.loginName' placeholder="请输入登录名" class="handle-input"></el-input>
    </el-form-item>
    <el-form-item label='手机号:'>
      <el-input :disabled="isview" class="handle-input" placeholder="手机号" v-model='adminParams.phone'></el-input>
    </el-form-item>  
    <el-form-item label='地址:'>
      <el-select :disabled="isview" v-model='adminParams.country' class="handle-input" @focus="getCountry" placeholder="请选择地址">
        <el-option v-for='(item,index) of country'
        :key='index' 
        :label='item.chineseName'
        :value='item.id'></el-option>
      </el-select>
    </el-form-item>
     <el-form-item label="新密码:">
      <el-input v-if='type!="add"' :disabled="isview" v-model="adminParams.password" auto-complete="off"  type="password" placeholder="请输入新密码(不更改无需输入)" class="handle-input"></el-input>
      <el-input v-else :disabled="isview" v-model="adminParams.password" auto-complete="off"  type="password" placeholder="请输入新密码" class="handle-input"></el-input>
    </el-form-item>
    <el-form-item label="密码确认:">
      <el-input v-if='type!="add"' :disabled="isview" v-model="repwd" auto-complete="off" @blur="enterPwd"   type="password"  placeholder="请再次输入新密码(不更改无需输入)"  class="handle-input"></el-input>
      <el-input v-else :disabled="isview" v-model="repwd" auto-complete="off" @blur="enterPwd"   type="password"  placeholder="请再次输入新密码"  class="handle-input"></el-input>
    </el-form-item>
    <el-form-item label='权限设置'>
      <el-checkbox-group 
      :disabled='isview'
      v-model="checkedOptions"
      @change='handleChange'
      >
      <el-checkbox v-for="city in optionSetting" :label="city.name" :key="city.value">{{city.name}}</el-checkbox>
    </el-checkbox-group>
    </el-form-item>
    <el-form-item label='邮箱:'>
      <el-input :disabled="isview" placeholder="输入邮箱地址" class="handle-input" v-model='adminParams.email'></el-input>
    </el-form-item>
     <el-form-item label="备注信息:"  >
      <el-input :disabled="isview" type="textarea"  :rows="4" v-model="adminParams.remark" placeholder="联系方式等备注信息..." auto-complete="off" class="handle-input"></el-input>
    </el-form-item>
    <!-- <el-form-item label="权限分配:">
      <span class="a_item" v-for='item in typeCenter'>
      <label>{{item.auth_name}}</label><el-switch v-model="authArr[item.auth_id]" on-text="打开" off-text="关闭"></el-switch>
      </span>
    </el-form-item> -->
  </el-form>
  <div slot="footer" class="dialog-footer">
     <el-button type="default" @click="closeEdit">关闭</el-button>
    <el-button type="danger" v-if='!isview' @click="updateMinfo">保存</el-button>
  </div>
</el-dialog>
<el-dialog :visible.sync='deleteModal' title='删除管理员'>
<span>确定删除吗？</span>
  <div slot="footer" class="dialog-footer">
     <el-button type="default" @click="deleteModal = false;">关闭</el-button>
    <el-button type="success" @click="deleteAdmin">删除</el-button>
  </div>
</el-dialog>



      
      <loading v-if='loading' :tip='tip'></loading>
    </div>
</template>

<script>
import * as rpConfig from "../../../../rpConfig/constant";
import { HttpReq } from "../../../service/server";
import {api,apiGet,apiPatch,apiPut,apiDelete} from "@/api/index";
import loading from "@/components/common/loading.vue";
var Server = new HttpReq();
export default {
  data() {
    return {
      optionSetting:[
        {
          value:'sbzx',
          name:'设备中心'
        },
        {
          value:'yhgl',
          name:'用户管理'
        },
        {
          value:'ddzx',
          name:'订单中心'
        },
        {
          value:'cwsj',
          name:'财务数据'
        },
        {
          value:'yygl',
          name:'运营管理'
        },
        {
          value:'czrz',
          name:'操作日志'
        }
      ],
      all_page:5,
      checkedOptions:[],
      isview:false,
      userAvatar:[],
      type:'',
      editId:'',
      country:[],
      loading:false,
      tip:'',
      canDo:true,
      deleteModal:false,
      repwd:'',//二次确认密码
      adminParams:{
        avatar :'',//头像
        country :'',//城市标识
        email :'',//电邮
        loginName :'',//登录名称
        password :'',//密码
        phone :'',//手机号
        remark :'',//备注
        username :'',//用户名
        status:'0',
        rights:'',//权限
      },
      params:{
        page:0,
        size:5,
        id:null,//管理员ID
        loginName:null,//管理员登录名
      },
      uploadURI: rpConfig.API_URI + "/Helpapi/uploadImg",
      editMinfo: false,
      dialogImageUrl: "",
      dialogVisible: false,
      userCenter: [
        { name: "BTM管理员1", auth: ["设备管理", "用户管理", "订单管理"] },
            { name: "BTM管理员2", auth: ["运营管理"] },
                { name: "BTM管理员3", auth: ["统计报表"] }
      
      ],
      typeCenter: [],
      authArr: {},
      deleteAdminId:'',
      unewdata: {
        mid: 0,
        name: "",
        pwd: "",
        repwd: "",
        remark: "",
        auth: [],
        avatar: "",
        showavatar: ""
      }
    };
  },
  created() {
    //  this.getData()
    //  this.getType()
  },
  components:{
    loading
  },
  computed: {
    userAuth() {
      return "test";
    }
  },
  methods: {
    deleteDialog(row){
      this.deleteModal=true;
      this.deleteAdminId=row.id;
    },
    deleteAdmin(row){
      this.loading=true;
      this.tip='删除管理员';
      apiDelete.admin.admin(this.deleteAdminId,{}).then(res=>{
        if(res.status==200){
          this.loading=false;
          //console.log(res);
          this.deleteModal=false;
          this.$message.success('删除成功');
          this.getList();
        }
      })
    },
    adminDetail(row){
      // //console.log(row);
      this.checkedOptions=[];
      this.type='edit';
      this.isview=true;
      this.userAvatar=[];
      this.editId=row.id;
      // //console.log(row);
      this.editMinfo=true;
      this.adminParams={
        avatar :row.avatar,//头像
        country :'',//城市标识
        email :row.email,//电邮
        loginName :row.loginName,//登录名称
        password :row.password,//密码
        phone :row.phone,//手机号
        remark :row.remark,//备注
        username :row.username,//用户名
        status:row.status,
        rights:'',//权限
      }
      // //console.log(this.adminParams)
      
      // this.adminParams=row;
      // this.adminParams.country=row.country.id;
      // this.$set(this.adminParams,'country',row.country.id)
      // //console.log(this.adminParams.country)
      if(typeof row['rights']=='string'){
        var rights=(row.rights&&row.rights.length)?row.rights.split(','):[];
        this.$set(this.adminParams,'rights',rights);
        this.checkedOptions=rights;
      }else if(typeof row['rights']=='object'){
        this.checkedOptions=row.rights;
      }
      this.userAvatar.push({name:row.username,url:row.avatar});
      this.getCountry().then(res=>{
        this.adminParams.country=row.country.id;
      })
    },
    getUsername(){
      if(this.adminParams.username==this.adminParams.loginName){
        return this.$message.warning('用户名和登录名不能一致');
      }
    },
    handleChange(val){
      this.checkedOptions=val;
    },
    exceed(){
            this.$message({message:'文件限制一个',type:'warning'})
        },
    enterPwd(){
      //
      if(this.adminParams.password!==this.repwd){
        this.canDo=false;
        this.$message({
          message:'两次密码输入不一致',
          type:'warning'
        })
      }else{
        this.canDo=true;
      }
    },
    handleCurrentChange(val){
      this.params.page=val-1;
      this.getList();
    },
    uploadAvatar(e){
      var self=this;
      var file=e.file;
      this.loading=true;
      this.tip='上传图片中';
      var reader=new FileReader();
      reader.readAsDataURL(file);
      reader.onload=function(){
          var params={
              data:this.result,
              filename:file.name
          }
          api.file.fileImg(params).then(res=>{
              // //console.log(res);
              self.adminParams.avatar =res.url;
              self.loading=false;
              // self.filelist.push(res);
          })
          // //console.log(self.filelist)
          file.value=null;
      }
    },
    editAdmin(row){
      this.type='edit';
      this.isview=false;
      this.userAvatar=[];
      this.checkedOptions=[];
      this.editId=row.id;
      // //console.log(row)
      this.editMinfo=true;this.adminParams={
        avatar :row.avatar,//头像
        country :'',//城市标识
        email :row.email,//电邮
        loginName :row.loginName,//登录名称
        password :row.password,//密码
        phone :row.phone,//手机号
        remark :row.remark,//备注
        username :row.username,//用户名
        status:row.status,
        rights:'',//权限
      };
      if(typeof row['rights']=='string'){
        var rights=(row.rights&&row.rights.length)?row.rights.split(','):[];
        this.$set(this.adminParams,'rights',rights);
        this.checkedOptions=rights;
      }else if(typeof row['rights']=='object'){
        this.checkedOptions=row.rights;
      }
      this.userAvatar.push({name:row.username,url:row.avatar});
      this.getCountry().then(res=>{
        this.adminParams.country=row.country.id;
      })
    },
    getCountry(page=0){
      return new Promise((resolve,reject)=>{
        var params={
        page:page,
        size:10,
      }
      apiGet.country.getCountry(params).then(res=>{
        // //console.log(res)
        this.country=res.content;
        resolve(res);
        // for(var i=0;i<4;i++){
        //   this.country.push(res.content)
        // }
      })
      })
      
    },
    handleAvatarSuccess(res) {
      if (res.code != 200) {
        this.$message.error(res.msg);
      } else {
        this.unewdata.showavatar = res.data.url;
        this.unewdata.avatar = res.data.saveUrl;
      }
    },
    getData() {
      let self = this;
      Server._POST(rpConfig.API_URI + "/system.Index/getMList", {}, function(
        res
      ) {
        self.userCenter = res.data;
      });
    },
    getType() {
      let self = this;
      Server._POST(rpConfig.API_URI + "/system.Index/getAllAuth", {}, function(
        response
      ) {
        self.typeCenter = response.data;
        for (let index of self.typeCenter) {
          if (self.unewdata.auth.includes(index.auth_id)) {
            self.$set(self.authArr, index.auth_id, true);
          } else {
            self.$set(self.authArr, index.auth_id, false);
          }
        }
      });
    },
    clearInfo() {
      this.unewdata = {
        mid: 0,
        name: "",
        pwd: "",
        repwd: "",
        remark: "",
        auth: []
      };
    },
    addNewAccount() {
      this.type='add';
      this.isview=false;
      this.editMinfo = true;
      this.adminParams={};
      this.userAvatar=[];
      apiGet.admin.adminRoles({}).then(res=>{
        //console.log(res);
      })
    },
    closeEdit() {
      this.clearInfo();
      this.editMinfo = false;
    },
    updateMinfo() {
      let self = this;
      this.loading=true;
      this.tip='正在操作';
      this.adminParams.rights=this.checkedOptions.join(',');
      if(this.type=='add'){
        api.admin.admin(this.adminParams).then(res=>{
          //console.log(res);
          this.loading=false;
          if(res.status){
            this.$message.success('新增操作成功');
            this.editMinfo = false;
            this.getList();
            this.adminParams={
              avatar :'',//头像
              country :'',//城市标识
              email :'',//电邮
              loginName :'',//登录名称
              password :'',//密码
              phone :'',//手机号
              remark :'',//备注
              username :'',//用户名
              status:'0',
            }
          }
        })
      }
      if(this.type=='edit'){
        apiPut.admin.admin(this.editId,this.adminParams).then(res=>{
          this.loading=false;
           this.$message.success('修改操作成功');
          this.editMinfo = false;
          this.getList();
        })
      }
      
      // self.unewdata.auth = [];
      // for (var key in self.authArr) {
      //   if (self.authArr[key]) {
      //     self.unewdata.auth.push(key);
      //   }
      // }
      // Server._POST(
      //   rpConfig.API_URI + "/system.Index/createAccount",
      //   self.unewdata,
      //   function(data) {
      //     self.$message.success(data.msg);
      //     setTimeout(() => {
      //       window.location.reload();
      //     }, 2000);
      //   }
      // );
    },

    editUInfo(uitem) {
      this.unewdata["mid"] = uitem.id;
      this.unewdata["name"] = uitem.name;
      this.unewdata["showavatar"] = uitem.avatar;
      this.unewdata["remark"] = uitem.remark;
      for (let index of uitem.authId) {
        this.$set(this.authArr, index, true);
      }
      this.editMinfo = true;
    },
    getList(){
      this.loading=true;
      this.tip='管理员列表';
      apiGet.admin.admin(this.params).then(res=>{
        this.userCenter=res.content;
        this.loading=false;
        this.all_page=res.totalElements;
      })
    },
    iceUinfo(uitem) {
      let self = this;
      this.$confirm(
        uitem.state == 1 ? "确认冻结该用户吗？" : "确认取消冻结该用户吗？"
      )
        .then(() => {
          Server._POST(
            rpConfig.API_URI + "/system.Index/iceAccount",
            { mid: uitem.id, type: uitem.state == 1 ? 0 : 1 },
            function(data) {
              self.$message.success(data.msg);
              setTimeout(() => {
                window.location.reload();
              }, 2000);
            }
          );
        })
        .catch(() => {});
    }
  },
  mounted () {
    this.getList();
  }
};
</script>

<style scoped>
img{
  vertical-align: bottom;
  margin:10px 0;
}
.a_item {
  display: inline-block;
  margin: 5px;
}
.a_item label {
  margin-right: 5px;
}
.auth_item {
  margin: 5px;
}
.u_list_item {
  margin-bottom: 10px;
}
.m_avatar {
  display: inline-block;
  height: 50px;
  width: 50px;
  vertical-align: middle;
  border-radius: 5px;
}
.btn-info {
  padding: 5px 10px;
}
.handle-box {
  margin-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9c2;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
img{
  /* vertical-align: middle; */
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/* .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
} */
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.handle-select {
  width: 120px;
}
.handle-input {
  width: 300px;
  display: inline-block;
}
</style>